// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 添加初始购物车数据
    cartItems: [
      { id: 1, name: '手机', price: 1000, quantity: 1 },
      { id: 2, name: '电脑', price: 2000, quantity: 1 },
      { id: 3, name: '键盘', price: 200, quantity: 2 }
    ]
  },
  getters: {
    cartTotalPrice(state) {
      return state.cartItems.reduce((total, item) => total + item.price * item.quantity, 0)
    }
  },
  mutations: {
    addToCart(state, item) {
      const existingItem = state.cartItems.find(cartItem => cartItem.id === item.id)
      if (existingItem) {
        existingItem.quantity += item.quantity
      } else {
        state.cartItems.push(item)
      }
    },
    removeFromCart(state, itemId) {
      state.cartItems = state.cartItems.filter(item => item.id !== itemId)
    },
    updateCartItemQuantity(state, { itemId, quantity }) {
      const item = state.cartItems.find(cartItem => cartItem.id === itemId)
      if (item) {
        item.quantity = quantity
      }
    }
  },
  actions: {
    addToCart({ commit }, item) {
      commit('addToCart', item)
    },
    removeFromCart({ commit }, itemId) {
      commit('removeFromCart', itemId)
    },
    updateCartItemQuantity({ commit }, payload) {
      commit('updateCartItemQuantity', payload)
    }
  }
})